<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : CustomService.php
 * Created on : 2023-3-24 15:18:15
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,不得商用;版权归属 HaoTeam Inc;
 */

namespace haoteam\service;

/**
 * Description of CustomService
 *
 * @author Tiger <1192851302@qq.com>
 */
class CustomService {

    protected $config = [];

    /**
     * 快速实例化模型
     * @author Tiger <1192851302@qq.com>
     * @param bool $singleton 是否单例
     * @return static
     */
    public static function instance($singleton = true) {
        $name = static::class;
        if (isset($GLOBALS['model'][$name]) and is_object($GLOBALS['model'][$name]) and $singleton) {
            $that = $GLOBALS['model'][$name];
        } else {
            $GLOBALS['model'][$name] = new static();
            $that = $GLOBALS['model'][$name];
        }
        $that->config = config('third.xiakexing');
        return $that;
    }

    /**
     * 登录
     * @author Tiger <1192851302@qq.com>
     * @param type $code
     * @return string appid
     * @return strimg unionid
     */
    public function session($code) {
        $thirdUserInfo = $this->request('api/third/authUserInfo', [], 'post', ['token' => $code, 'company-code' => 16]);
        $userInfo['mobile'] = $thirdUserInfo['mobile'];
        $userInfo['nickname'] = $thirdUserInfo['nickname'];
        $userInfo['avatar'] = $this->config['api'].$thirdUserInfo['avatar'];
        //$userInfo['gender'] = $thirdUserInfo['user_sex'];
        $userInfo['openid'] = $thirdUserInfo['id'];
        //$userInfo['unionId'] = $thirdUserInfo['unquied'];
        return $userInfo;
    }

    /**
     * 请求
     * @author Tiger <1192851302@qq.com>
     * @param type $path
     * @param type $options
     * @param type $method
     * @param type $headers
     * @return type
     * @throws \think\Exception
     */
    public function request($path, $options, $method = 'json', $headers = []) {
        $ret = HttpService::instance()->{$method}($this->config['api'] . $path, $options, $headers);
        if ($ret['code'] == 200) {
            return $ret['data'] ?? $ret;
        }
        throw new \think\Exception(json_encode($ret, JSON_UNESCAPED_UNICODE));
    }
}
